package region

import (
	"context"

	"mall/common/modelx"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/backend/common/utils/pointy"
	"mall/service/setting/rpc/internal/svc"
	"mall/service/setting/rpc/internal/utils/errorhandler"
	"mall/service/setting/rpc/types/setting"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendGetRegionByIdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendGetRegionByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendGetRegionByIdLogic {
	return &BackendGetRegionByIdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// group: region
func (l *BackendGetRegionByIdLogic) BackendGetRegionById(in *setting.IDReq) (*setting.RegionInfo, error) {
	if in.Id == uint64(1000000) {
		l.svcCtx.SysRegion.DiagnoseMetum(l.ctx)
	}

	if in.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	res, err := l.svcCtx.SysRegion.FindOne(l.ctx, in.Id)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	return &setting.RegionInfo{
		Id:        &res.ID,
		ParentId:  &res.ParentID,
		Level:     pointy.GetPointer(uint32(res.Level)),
		Sort:      pointy.GetPointer(uint32(res.Sort)),
		Name:      &res.Name,
		Code:      &res.Code,
		Region:    &res.Region,
		Status:    pointy.GetPointer(uint32(res.Status)),
		CreatedAt: pointy.GetPointer(modelx.FormatTime(res.CreatedAt, "")),
		UpdatedAt: pointy.GetPointer(modelx.FormatTime(res.UpdatedAt, "")),
		DeletedAt: pointy.GetPointer(modelx.FormatNullDotTime(res.DeletedAt, "")),
	}, nil
}
